import Modal, {
  modalProps,
  type ModalProps,
} from "ant-design-vue/es/modal/Modal";
import { defineComponent, ref, watch, type PropType } from "vue";
import type { ProColumnsType } from "../interface";
import ProForm from "../pro-form";
import type { FormInstance } from "ant-design-vue/es/form/Form";
import { Button } from "ant-design-vue";

export default defineComponent({
  name: "AddAndDetail",
  props: {
    /**弹窗标题 */
    title: {
      required: true,
      type: String,
    },
    /**弹窗是否弹出 */
    open: {
      type: Boolean,
      default: false,
    },
    /**表单列配置 */
    columns: {
      required: true,
      type: Array as PropType<ProColumnsType<any>>,
    },
    /**表单/详情的初始值请求函数 */
    request: {
      required: true,
      type: Function as PropType<() => Promise<any>>,
    },
    /**表单提交的回调函数 */
    onFinish: {
      required: true,
      type: Function as PropType<
        (values: Record<string, any>) => Promise<boolean>
      >,
    },
    /**弹窗Modal的配置项 */
    modalProps: {
      type: Object as PropType<ModalProps>,
      default: () => ({}),
    },
    /**表单模式，write为写入模式，read为只读模式 */
    mode: {
      type: String as PropType<"write" | "read">,
      default: "write",
    },
  },
  emits: [
    /**控制弹窗是否弹出 */
    "update:open",
  ],
  setup(props, ctx) {
    const formRef = ref<FormInstance>();
    const initialValues = ref<Record<string, any>>({});

    watch(
      () => [props.open, formRef.value],
      (newVal) => {
        if (!newVal[1]) {
          return;
        }
        if (newVal[0]) {
          newVal[1].resetFields();
          props.request().then((res) => {
            initialValues.value = res;
            console.log("initialValues.value", initialValues.value);
          });
          return;
        }
      },
      { immediate: true } // 非modal模式需要
    );

    const content = () => (
      <div class="add-and-detail-content">
        <ProForm
          ref={formRef}
          initialValues={initialValues.value}
          columns={props.columns}
          mode={props.mode}
        />
      </div>
    );

    const btnloading = ref<boolean>(false);

    return () => (
      <Modal
        {...props.modalProps}
        title={props.title}
        open={props.open}
        onCancel={() => ctx.emit("update:open", false)}
        footer={[
          props.mode === "write" && (
            <Button
              key="submit"
              type="primary"
              loading={btnloading.value}
              onClick={() => {
                btnloading.value = true;
                formRef.value?.validate().then((v) => {
                  props
                    .onFinish(v)
                    .then((bool) => {
                      ctx.emit("update:open", !bool);
                    })
                    .finally(() => {
                      btnloading.value = false;
                    });
                });
              }}
            >
              保存
            </Button>
          ),
          <Button onClick={() => ctx.emit("update:open", false)}>取消</Button>,
        ]}
      >
        {content()}
      </Modal>
    );
  },
});
